<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Image Segmentation with Distance Transform and Watershed Algorithm</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../d7/da8/tutorial_table_of_content_imgproc.html">Image Processing (imgproc module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Image Segmentation with Distance Transform and Watershed Algorithm </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../dc/d48/tutorial_point_polygon_test.html">Point Polygon Test</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../de/d3c/tutorial_out_of_focus_deblur_filter.html">Out-of-focus Deblur Filter</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Theodore Tsesmelis </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<h2>Goal </h2>
<p>In this tutorial you will learn how to:</p>
<ul>
<li>Use the OpenCV function <a class="el" href="../../d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04">cv::filter2D</a> in order to perform some laplacian filtering for image sharpening</li>
<li>Use the OpenCV function <a class="el" href="../../d7/d1b/group__imgproc__misc.html#ga8a0b7fdfcb7a13dde018988ba3a43042">cv::distanceTransform</a> in order to obtain the derived representation of a binary image, where the value of each pixel is replaced by its distance to the nearest background pixel</li>
<li>Use the OpenCV function <a class="el" href="../../d3/d47/group__imgproc__segmentation.html#ga3267243e4d3f95165d55a618c65ac6e1">cv::watershed</a> in order to isolate objects in the image from the background</li>
</ul>
<h2>Theory </h2>
<h2>Code </h2>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'><p> This tutorial code's is shown lines below. You can also download it from <a href="https://github.com/opencv/opencv/tree/master/samples/cpp/tutorial_code/ImgTrans/imageSegmentation.cpp">here</a>. </p><div class="fragment"><div class="line"></div><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d0/d9c/core_2include_2opencv2_2core_8hpp.html">opencv2/core.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d1/d4f/imgproc_2include_2opencv2_2imgproc_8hpp.html">opencv2/imgproc.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d4/dd5/highgui_8hpp.html">opencv2/highgui.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span>std;</div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span> argc, <span class="keywordtype">char</span> *argv[])</div><div class="line">{</div><div class="line">    <span class="comment">// Load the image</span></div><div class="line">    <a class="code" href="../../d0/d2e/classcv_1_1CommandLineParser.html">CommandLineParser</a> parser( argc, argv, <span class="stringliteral">&quot;{@input | cards.png | input image}&quot;</span> );</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;( <span class="stringliteral">&quot;@input&quot;</span> ) ) );</div><div class="line">    <span class="keywordflow">if</span>( src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abbec3525a852e77998aba034813fded4">empty</a>() )</div><div class="line">    {</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Could not open or find the image!\n&quot;</span> &lt;&lt; endl;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Usage: &quot;</span> &lt;&lt; argv[0] &lt;&lt; <span class="stringliteral">&quot; &lt;Input image&gt;&quot;</span> &lt;&lt; endl;</div><div class="line">        <span class="keywordflow">return</span> -1;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Show the source image</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Source Image&quot;</span>, src);</div><div class="line"></div><div class="line">    <span class="comment">// Change the background from white to black, since that will help later to extract</span></div><div class="line">    <span class="comment">// better results during the use of Distance Transform</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> <a class="code" href="../../da/dd3/group__gapi__math.html#gaba076d51941328cb7ca9348b7b535220">mask</a>;</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga48af0ab51e36436c5d04340e036ce981">inRange</a>(src, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255, 255, 255), <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255, 255, 255), mask);</div><div class="line">    src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0440e2a164c0b0d8462fb1e487be9876">setTo</a>(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0, 0, 0), mask);</div><div class="line"></div><div class="line">    <span class="comment">// Show output image</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Black Background Image&quot;</span>, src);</div><div class="line"></div><div class="line">    <span class="comment">// Create a kernel that we will use to sharpen our image</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> kernel = (<a class="code" href="../../df/dfc/classcv_1_1Mat__.html">Mat_&lt;float&gt;</a>(3,3) &lt;&lt;</div><div class="line">                  1,  1, 1,</div><div class="line">                  1, -8, 1,</div><div class="line">                  1,  1, 1); <span class="comment">// an approximation of second derivative, a quite strong kernel</span></div><div class="line"></div><div class="line">    <span class="comment">// do the laplacian filtering as it is</span></div><div class="line">    <span class="comment">// well, we need to convert everything in something more deeper then CV_8U</span></div><div class="line">    <span class="comment">// because the kernel has some negative values,</span></div><div class="line">    <span class="comment">// and we can expect in general to have a Laplacian image with negative values</span></div><div class="line">    <span class="comment">// BUT a 8bits unsigned int (the one we are working with) can contain values from 0 to 255</span></div><div class="line">    <span class="comment">// so the possible negative number will be truncated</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> imgLaplacian;</div><div class="line">    <a class="code" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D</a>(src, imgLaplacian, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga4a3def5d72b74bed31f5f8ab7676099c">CV_32F</a>, kernel);</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> sharp;</div><div class="line">    src.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#adf88c60c5b4980e05bb556080916978b">convertTo</a>(sharp, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga4a3def5d72b74bed31f5f8ab7676099c">CV_32F</a>);</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> imgResult = sharp - imgLaplacian;</div><div class="line"></div><div class="line">    <span class="comment">// convert back to 8bits gray scale</span></div><div class="line">    imgResult.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#adf88c60c5b4980e05bb556080916978b">convertTo</a>(imgResult, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a>);</div><div class="line">    imgLaplacian.convertTo(imgLaplacian, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a>);</div><div class="line"></div><div class="line">    <span class="comment">// imshow( &quot;Laplace Filtered Image&quot;, imgLaplacian );</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;New Sharped Image&quot;</span>, imgResult );</div><div class="line"></div><div class="line">    <span class="comment">// Create binary image from source image</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> bw;</div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>(imgResult, bw, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0a353a4b8db9040165db4dacb5bcefb6ea">COLOR_BGR2GRAY</a>);</div><div class="line">    <a class="code" href="../../d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">threshold</a>(bw, bw, 40, 255, <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ggaa9e58d2860d4afa658ef70a9b1115576a147222a96556ebc1d948b372bcd7ac59">THRESH_BINARY</a> | <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ggaa9e58d2860d4afa658ef70a9b1115576a95251923e8e22f368ffa86ba8bce87ff">THRESH_OTSU</a>);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Binary Image&quot;</span>, bw);</div><div class="line"></div><div class="line">    <span class="comment">// Perform the distance transform algorithm</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> dist;</div><div class="line">    <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ga8a0b7fdfcb7a13dde018988ba3a43042">distanceTransform</a>(bw, dist, <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ggaa2bfbebbc5c320526897996aafa1d8ebaff0d1f5be0fc152a56a9b9716d158b96">DIST_L2</a>, 3);</div><div class="line"></div><div class="line">    <span class="comment">// Normalize the distance image for range = {0.0, 1.0}</span></div><div class="line">    <span class="comment">// so we can visualize and threshold it</span></div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1b6a396a456c8b6c6e4afd8591560d80">normalize</a>(dist, dist, 0, 1.0, <a class="code" href="../../d2/de8/group__core__array.html#ggad12cefbcb5291cf958a85b4b67b6149fa9f0c1c342a18114d47b516a88e29822e">NORM_MINMAX</a>);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Distance Transform Image&quot;</span>, dist);</div><div class="line"></div><div class="line">    <span class="comment">// Threshold to obtain the peaks</span></div><div class="line">    <span class="comment">// This will be the markers for the foreground objects</span></div><div class="line">    <a class="code" href="../../d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">threshold</a>(dist, dist, 0.4, 1.0, <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ggaa9e58d2860d4afa658ef70a9b1115576a147222a96556ebc1d948b372bcd7ac59">THRESH_BINARY</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Dilate a bit the dist image</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> kernel1 = Mat::ones(3, 3, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);</div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga4ff0f3318642c4f469d0e11f242f3b6c">dilate</a>(dist, dist, kernel1);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Peaks&quot;</span>, dist);</div><div class="line"></div><div class="line">    <span class="comment">// Create the CV_8U version of the distance image</span></div><div class="line">    <span class="comment">// It is needed for findContours()</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> dist_8u;</div><div class="line">    dist.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#adf88c60c5b4980e05bb556080916978b">convertTo</a>(dist_8u, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Find total markers</span></div><div class="line">    vector&lt;vector&lt;Point&gt; &gt; contours;</div><div class="line">    <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0">findContours</a>(dist_8u, contours, <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga819779b9857cc2f8601e6526a3a5bc71aa7adc6d6608609fd84650f71b954b981">RETR_EXTERNAL</a>, <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga4303f45752694956374734a03c54d5ffa5f2883048e654999209f88ba04c302f5">CHAIN_APPROX_SIMPLE</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Create the marker image for the watershed algorithm</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> markers = Mat::zeros(dist.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a146f8e8dda07d1365a575ab83d9828d1">size</a>(), <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga4067910fc388075c3ea3aa14393e83b9">CV_32S</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Draw the foreground markers</span></div><div class="line">    <span class="keywordflow">for</span> (<span class="keywordtype">size_t</span> i = 0; i &lt; contours.size(); i++)</div><div class="line">    {</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc">drawContours</a>(markers, contours, static_cast&lt;int&gt;(i), <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(static_cast&lt;int&gt;(i)+1), -1);</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Draw the background marker</span></div><div class="line">    <a class="code" href="../../d9/db7/group__datasets__gr.html#gga610754124ced68d1f05760b5948fbb76a6f0d8b2d9e3e947b2a5c1eff9e81ee95">circle</a>(markers, <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(5,5), 3, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255), -1);</div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> markers8u;</div><div class="line">    markers.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#adf88c60c5b4980e05bb556080916978b">convertTo</a>(markers8u, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>, 10);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Markers&quot;</span>, markers8u);</div><div class="line"></div><div class="line">    <span class="comment">// Perform the watershed algorithm</span></div><div class="line">    <a class="code" href="../../d3/d47/group__imgproc__segmentation.html#ga3267243e4d3f95165d55a618c65ac6e1">watershed</a>(imgResult, markers);</div><div class="line"></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> mark;</div><div class="line">    markers.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#adf88c60c5b4980e05bb556080916978b">convertTo</a>(mark, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga0002cf8b418479f4cb49a75442baee2f">bitwise_not</a>(mark, mark);</div><div class="line">    <span class="comment">//    imshow(&quot;Markers_v2&quot;, mark); // uncomment this if you want to see how the mark</span></div><div class="line">    <span class="comment">// image looks like at that point</span></div><div class="line"></div><div class="line">    <span class="comment">// Generate random colors</span></div><div class="line">    vector&lt;Vec3b&gt; colors;</div><div class="line">    <span class="keywordflow">for</span> (<span class="keywordtype">size_t</span> i = 0; i &lt; contours.size(); i++)</div><div class="line">    {</div><div class="line">        <span class="keywordtype">int</span> b = <a class="code" href="../../d2/de8/group__core__array.html#ga75843061d150ad6564b5447e38e57722">theRNG</a>().<a class="code" href="../../d1/dd6/classcv_1_1RNG.html#acde197860cea91e5aa896be8719457ae">uniform</a>(0, 256);</div><div class="line">        <span class="keywordtype">int</span> g = <a class="code" href="../../d2/de8/group__core__array.html#ga75843061d150ad6564b5447e38e57722">theRNG</a>().<a class="code" href="../../d1/dd6/classcv_1_1RNG.html#acde197860cea91e5aa896be8719457ae">uniform</a>(0, 256);</div><div class="line">        <span class="keywordtype">int</span> r = <a class="code" href="../../d2/de8/group__core__array.html#ga75843061d150ad6564b5447e38e57722">theRNG</a>().<a class="code" href="../../d1/dd6/classcv_1_1RNG.html#acde197860cea91e5aa896be8719457ae">uniform</a>(0, 256);</div><div class="line"></div><div class="line">        colors.push_back(<a class="code" href="../../dc/d84/group__core__basic.html#ga7e6060c0b8d48459964df6e1eb524c03">Vec3b</a>((<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>)b, (<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>)g, (<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>)r));</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Create the result image</span></div><div class="line">    <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> dst = Mat::zeros(markers.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a146f8e8dda07d1365a575ab83d9828d1">size</a>(), <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Fill labeled objects with random colors</span></div><div class="line">    <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; markers.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#abed816466c45234254d25bc59c31245e">rows</a>; i++)</div><div class="line">    {</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 0; j &lt; markers.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#aa3e5a47585c9ef6a0842556739155e3e">cols</a>; j++)</div><div class="line">        {</div><div class="line">            <span class="keywordtype">int</span> <a class="code" href="../../d9/db7/group__datasets__gr.html#gga82775e152f8a74c5fe06f5a7343e0233a9dfc90ef6dc3ba62850d76cc3534572c">index</a> = markers.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#aa5d20fc86d41d59e4d71ae93daee9726">at</a>&lt;<span class="keywordtype">int</span>&gt;(i,j);</div><div class="line">            <span class="keywordflow">if</span> (index &gt; 0 &amp;&amp; index &lt;= static_cast&lt;int&gt;(contours.size()))</div><div class="line">            {</div><div class="line">                dst.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#aa5d20fc86d41d59e4d71ae93daee9726">at</a>&lt;<a class="code" href="../../d6/dcf/classcv_1_1Vec.html">Vec3b</a>&gt;(i,j) = colors[index-1];</div><div class="line">            }</div><div class="line">        }</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Visualize the final image</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Final Result&quot;</span>, dst);</div><div class="line"></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">waitKey</a>();</div><div class="line">    <span class="keywordflow">return</span> 0;</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'><p> This tutorial code's is shown lines below. You can also download it from <a href="https://github.com/opencv/opencv/tree/master/samples/java/tutorial_code/ImgTrans/distance_transformation/ImageSegmentationDemo.java">here</a> </p><div class="fragment"><div class="line"><span class="keyword">import</span> java.util.ArrayList;</div><div class="line"><span class="keyword">import</span> java.util.List;</div><div class="line"><span class="keyword">import</span> java.util.Random;</div><div class="line"></div><div class="line"><span class="keyword">import</span> org.opencv.core.Core;</div><div class="line"><span class="keyword">import</span> org.opencv.core.CvType;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Mat;</div><div class="line"><span class="keyword">import</span> org.opencv.core.MatOfPoint;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Point;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Scalar;</div><div class="line"><span class="keyword">import</span> org.opencv.highgui.HighGui;</div><div class="line"><span class="keyword">import</span> org.opencv.imgcodecs.Imgcodecs;</div><div class="line"><span class="keyword">import</span> org.opencv.imgproc.Imgproc;</div><div class="line"></div><div class="line"><span class="keyword">class </span>ImageSegmentation {</div><div class="line">    <span class="keyword">public</span> <span class="keywordtype">void</span> run(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Load the image</span></div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> filename = args.length &gt; 0 ? args[0] : <span class="stringliteral">&quot;../data/cards.png&quot;</span>;</div><div class="line">        Mat srcOriginal = Imgcodecs.imread(filename);</div><div class="line">        <span class="keywordflow">if</span> (srcOriginal.empty()) {</div><div class="line">            System.err.println(<span class="stringliteral">&quot;Cannot read image: &quot;</span> + filename);</div><div class="line">            System.exit(0);</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Show source image</span></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Source Image&quot;</span>, srcOriginal);</div><div class="line"></div><div class="line">        <span class="comment">// Change the background from white to black, since that will help later to</span></div><div class="line">        <span class="comment">// extract</span></div><div class="line">        <span class="comment">// better results during the use of Distance Transform</span></div><div class="line">        Mat src = srcOriginal.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#adff2ea98da45eae0833e73582dd4a660">clone</a>();</div><div class="line">        byte[] srcData = <span class="keyword">new</span> byte[(int) (src.total() * src.channels())];</div><div class="line">        src.get(0, 0, srcData);</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; src.rows(); i++) {</div><div class="line">            <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 0; j &lt; src.cols(); j++) {</div><div class="line">                <span class="keywordflow">if</span> (srcData[(i * src.cols() + j) * 3] == (byte) 255 &amp;&amp; srcData[(i * src.cols() + j) * 3 + 1] == (byte) 255</div><div class="line">                        &amp;&amp; srcData[(i * src.cols() + j) * 3 + 2] == (byte) 255) {</div><div class="line">                    srcData[(i * src.cols() + j) * 3] = 0;</div><div class="line">                    srcData[(i * src.cols() + j) * 3 + 1] = 0;</div><div class="line">                    srcData[(i * src.cols() + j) * 3 + 2] = 0;</div><div class="line">                }</div><div class="line">            }</div><div class="line">        }</div><div class="line">        src.put(0, 0, srcData);</div><div class="line"></div><div class="line">        <span class="comment">// Show output image</span></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Black Background Image&quot;</span>, src);</div><div class="line"></div><div class="line">        <span class="comment">// Create a kernel that we will use to sharpen our image</span></div><div class="line">        Mat kernel = <span class="keyword">new</span> Mat(3, 3, CvType.CV_32F);</div><div class="line">        <span class="comment">// an approximation of second derivative, a quite strong kernel</span></div><div class="line">        <span class="keywordtype">float</span>[] kernelData = <span class="keyword">new</span> <span class="keywordtype">float</span>[(int) (kernel.total() * kernel.channels())];</div><div class="line">        kernelData[0] = 1; kernelData[1] = 1; kernelData[2] = 1;</div><div class="line">        kernelData[3] = 1; kernelData[4] = -8; kernelData[5] = 1;</div><div class="line">        kernelData[6] = 1; kernelData[7] = 1; kernelData[8] = 1;</div><div class="line">        kernel.put(0, 0, kernelData);</div><div class="line"></div><div class="line">        <span class="comment">// do the laplacian filtering as it is</span></div><div class="line">        <span class="comment">// well, we need to convert everything in something more deeper then CV_8U</span></div><div class="line">        <span class="comment">// because the kernel has some negative values,</span></div><div class="line">        <span class="comment">// and we can expect in general to have a Laplacian image with negative values</span></div><div class="line">        <span class="comment">// BUT a 8bits unsigned int (the one we are working with) can contain values</span></div><div class="line">        <span class="comment">// from 0 to 255</span></div><div class="line">        <span class="comment">// so the possible negative number will be truncated</span></div><div class="line">        Mat imgLaplacian = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.filter2D(src, imgLaplacian, CvType.CV_32F, kernel);</div><div class="line">        Mat sharp = <span class="keyword">new</span> Mat();</div><div class="line">        src.convertTo(sharp, CvType.CV_32F);</div><div class="line">        Mat imgResult = <span class="keyword">new</span> Mat();</div><div class="line">        Core.subtract(sharp, imgLaplacian, imgResult);</div><div class="line"></div><div class="line">        <span class="comment">// convert back to 8bits gray scale</span></div><div class="line">        imgResult.convertTo(imgResult, CvType.CV_8UC3);</div><div class="line">        imgLaplacian.convertTo(imgLaplacian, CvType.CV_8UC3);</div><div class="line"></div><div class="line">        <span class="comment">// imshow( &quot;Laplace Filtered Image&quot;, imgLaplacian );</span></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;New Sharped Image&quot;</span>, imgResult);</div><div class="line"></div><div class="line">        <span class="comment">// Create binary image from source image</span></div><div class="line">        Mat bw = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.cvtColor(imgResult, bw, Imgproc.COLOR_BGR2GRAY);</div><div class="line">        Imgproc.threshold(bw, bw, 40, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);</div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Binary Image&quot;</span>, bw);</div><div class="line"></div><div class="line">        <span class="comment">// Perform the distance transform algorithm</span></div><div class="line">        Mat dist = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.distanceTransform(bw, dist, Imgproc.DIST_L2, 3);</div><div class="line"></div><div class="line">        <span class="comment">// Normalize the distance image for range = {0.0, 1.0}</span></div><div class="line">        <span class="comment">// so we can visualize and threshold it</span></div><div class="line">        Core.normalize(dist, dist, 0.0, 1.0, Core.NORM_MINMAX);</div><div class="line">        Mat distDisplayScaled = <span class="keyword">new</span> Mat();</div><div class="line">        Core.multiply(dist, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255), distDisplayScaled);</div><div class="line">        Mat distDisplay = <span class="keyword">new</span> Mat();</div><div class="line">        distDisplayScaled.convertTo(distDisplay, CvType.CV_8U);</div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Distance Transform Image&quot;</span>, distDisplay);</div><div class="line"></div><div class="line">        <span class="comment">// Threshold to obtain the peaks</span></div><div class="line">        <span class="comment">// This will be the markers for the foreground objects</span></div><div class="line">        Imgproc.threshold(dist, dist, 0.4, 1.0, Imgproc.THRESH_BINARY);</div><div class="line"></div><div class="line">        <span class="comment">// Dilate a bit the dist image</span></div><div class="line">        Mat kernel1 = Mat.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a69ae0402d116fc9c71908d8508dc2f09">ones</a>(3, 3, CvType.CV_8U);</div><div class="line">        Imgproc.dilate(dist, dist, kernel1);</div><div class="line">        Mat distDisplay2 = <span class="keyword">new</span> Mat();</div><div class="line">        dist.convertTo(distDisplay2, CvType.CV_8U);</div><div class="line">        Core.multiply(distDisplay2, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255), distDisplay2);</div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Peaks&quot;</span>, distDisplay2);</div><div class="line"></div><div class="line">        <span class="comment">// Create the CV_8U version of the distance image</span></div><div class="line">        <span class="comment">// It is needed for findContours()</span></div><div class="line">        Mat dist_8u = <span class="keyword">new</span> Mat();</div><div class="line">        dist.convertTo(dist_8u, CvType.CV_8U);</div><div class="line"></div><div class="line">        <span class="comment">// Find total markers</span></div><div class="line">        List&lt;MatOfPoint&gt; contours = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">        Mat hierarchy = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.findContours(dist_8u, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);</div><div class="line"></div><div class="line">        <span class="comment">// Create the marker image for the watershed algorithm</span></div><div class="line">        Mat markers = Mat.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0b57b6a326c8876d944d188a46e0f556">zeros</a>(dist.size(), CvType.CV_32S);</div><div class="line"></div><div class="line">        <span class="comment">// Draw the foreground markers</span></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; contours.size(); i++) {</div><div class="line">            Imgproc.drawContours(markers, contours, i, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(i + 1), -1);</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Draw the background marker</span></div><div class="line">        Mat markersScaled = <span class="keyword">new</span> Mat();</div><div class="line">        markers.convertTo(markersScaled, CvType.CV_32F);</div><div class="line">        Core.normalize(markersScaled, markersScaled, 0.0, 255.0, Core.NORM_MINMAX);</div><div class="line">        Imgproc.circle(markersScaled, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(5, 5), 3, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255, 255, 255), -1);</div><div class="line">        Mat markersDisplay = <span class="keyword">new</span> Mat();</div><div class="line">        markersScaled.convertTo(markersDisplay, CvType.CV_8U);</div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Markers&quot;</span>, markersDisplay);</div><div class="line">        Imgproc.circle(markers, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(5, 5), 3, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255, 255, 255), -1);</div><div class="line"></div><div class="line">        <span class="comment">// Perform the watershed algorithm</span></div><div class="line">        Imgproc.watershed(imgResult, markers);</div><div class="line"></div><div class="line">        Mat mark = Mat.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0b57b6a326c8876d944d188a46e0f556">zeros</a>(markers.size(), CvType.CV_8U);</div><div class="line">        markers.convertTo(mark, CvType.CV_8UC1);</div><div class="line">        Core.bitwise_not(mark, mark);</div><div class="line">        <span class="comment">// imshow(&quot;Markers_v2&quot;, mark); // uncomment this if you want to see how the mark</span></div><div class="line">        <span class="comment">// image looks like at that point</span></div><div class="line"></div><div class="line">        <span class="comment">// Generate random colors</span></div><div class="line">        Random rng = <span class="keyword">new</span> Random(12345);</div><div class="line">        List&lt;Scalar&gt; colors = <span class="keyword">new</span> ArrayList&lt;&gt;(contours.size());</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; contours.size(); i++) {</div><div class="line">            <span class="keywordtype">int</span> b = rng.nextInt(256);</div><div class="line">            <span class="keywordtype">int</span> g = rng.nextInt(256);</div><div class="line">            <span class="keywordtype">int</span> r = rng.nextInt(256);</div><div class="line"></div><div class="line">            colors.add(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(b, g, r));</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Create the result image</span></div><div class="line">        Mat dst = Mat.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#a0b57b6a326c8876d944d188a46e0f556">zeros</a>(markers.size(), CvType.CV_8UC3);</div><div class="line">        byte[] dstData = <span class="keyword">new</span> byte[(int) (dst.total() * dst.channels())];</div><div class="line">        dst.get(0, 0, dstData);</div><div class="line"></div><div class="line">        <span class="comment">// Fill labeled objects with random colors</span></div><div class="line">        <span class="keywordtype">int</span>[] markersData = <span class="keyword">new</span> <span class="keywordtype">int</span>[(int) (markers.total() * markers.channels())];</div><div class="line">        markers.get(0, 0, markersData);</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; markers.rows(); i++) {</div><div class="line">            <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 0; j &lt; markers.cols(); j++) {</div><div class="line">                <span class="keywordtype">int</span> <a class="code" href="../../d9/db7/group__datasets__gr.html#gga82775e152f8a74c5fe06f5a7343e0233a9dfc90ef6dc3ba62850d76cc3534572c">index</a> = markersData[i * markers.cols() + j];</div><div class="line">                <span class="keywordflow">if</span> (index &gt; 0 &amp;&amp; index &lt;= contours.size()) {</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 0] = (byte) colors.get(index - 1).val[0];</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 1] = (byte) colors.get(index - 1).val[1];</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 2] = (byte) colors.get(index - 1).val[2];</div><div class="line">                } <span class="keywordflow">else</span> {</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 0] = 0;</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 1] = 0;</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 2] = 0;</div><div class="line">                }</div><div class="line">            }</div><div class="line">        }</div><div class="line">        dst.put(0, 0, dstData);</div><div class="line"></div><div class="line">        <span class="comment">// Visualize the final image</span></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Final Result&quot;</span>, dst);</div><div class="line"></div><div class="line">        HighGui.waitKey();</div><div class="line">        System.exit(0);</div><div class="line">    }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">class </span>ImageSegmentationDemo {</div><div class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">        <span class="comment">// Load the native OpenCV library</span></div><div class="line">        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);</div><div class="line"></div><div class="line">        <span class="keyword">new</span> ImageSegmentation().run(args);</div><div class="line">    }</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'><p> This tutorial code's is shown lines below. You can also download it from <a href="https://github.com/opencv/opencv/tree/master/samples/python/tutorial_code/ImgTrans/distance_transformation/imageSegmentation.py">here</a> </p><div class="fragment"><div class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> print_function</div><div class="line"><span class="keyword">import</span> cv2 <span class="keyword">as</span> cv</div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"><span class="keyword">import</span> argparse</div><div class="line"><span class="keyword">import</span> random <span class="keyword">as</span> rng</div><div class="line"></div><div class="line">rng.seed(12345)</div><div class="line"></div><div class="line"></div><div class="line">parser = argparse.ArgumentParser(description=<span class="stringliteral">&#39;Code for Image Segmentation with Distance Transform and Watershed Algorithm.\</span></div><div class="line"><span class="stringliteral">    Sample code showing how to segment overlapping objects using Laplacian filtering, \</span></div><div class="line"><span class="stringliteral">    in addition to Watershed and Distance Transformation&#39;</span>)</div><div class="line">parser.add_argument(<span class="stringliteral">&#39;--input&#39;</span>, help=<span class="stringliteral">&#39;Path to input image.&#39;</span>, default=<span class="stringliteral">&#39;cards.png&#39;</span>)</div><div class="line">args = parser.parse_args()</div><div class="line"></div><div class="line">src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(args.input))</div><div class="line"><span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">    <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&#39;Could not open or find the image:&#39;</span>, args.input)</div><div class="line">    exit(0)</div><div class="line"></div><div class="line"><span class="comment"># Show source image</span></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Source Image&#39;</span>, src)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">src[np.all(src == 255, axis=2)] = 0</div><div class="line"></div><div class="line"><span class="comment"># Show output image</span></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Black Background Image&#39;</span>, src)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]], dtype=np.float32)</div><div class="line"></div><div class="line"><span class="comment"># do the laplacian filtering as it is</span></div><div class="line"><span class="comment"># well, we need to convert everything in something more deeper then CV_8U</span></div><div class="line"><span class="comment"># because the kernel has some negative values,</span></div><div class="line"><span class="comment"># and we can expect in general to have a Laplacian image with negative values</span></div><div class="line"><span class="comment"># BUT a 8bits unsigned int (the one we are working with) can contain values from 0 to 255</span></div><div class="line"><span class="comment"># so the possible negative number will be truncated</span></div><div class="line">imgLaplacian = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04">cv.filter2D</a>(src, cv.CV_32F, kernel)</div><div class="line">sharp = np.float32(src)</div><div class="line">imgResult = sharp - imgLaplacian</div><div class="line"></div><div class="line"><span class="comment"># convert back to 8bits gray scale</span></div><div class="line">imgResult = np.clip(imgResult, 0, 255)</div><div class="line">imgResult = imgResult.astype(<span class="stringliteral">&#39;uint8&#39;</span>)</div><div class="line">imgLaplacian = np.clip(imgLaplacian, 0, 255)</div><div class="line">imgLaplacian = np.uint8(imgLaplacian)</div><div class="line"></div><div class="line"><span class="comment">#cv.imshow(&#39;Laplace Filtered Image&#39;, imgLaplacian)</span></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;New Sharped Image&#39;</span>, imgResult)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">bw = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(imgResult, cv.COLOR_BGR2GRAY)</div><div class="line">_, bw = <a class="code" href="../../d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">cv.threshold</a>(bw, 40, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Binary Image&#39;</span>, bw)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">dist = <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ga25c259e7e2fa2ac70de4606ea800f12f">cv.distanceTransform</a>(bw, cv.DIST_L2, 3)</div><div class="line"></div><div class="line"><span class="comment"># Normalize the distance image for range = {0.0, 1.0}</span></div><div class="line"><span class="comment"># so we can visualize and threshold it</span></div><div class="line"><a class="code" href="../../d2/de8/group__core__array.html#ga7bcf47a1df78cf575162e0aed44960cb">cv.normalize</a>(dist, dist, 0, 1.0, cv.NORM_MINMAX)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Distance Transform Image&#39;</span>, dist)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">_, dist = <a class="code" href="../../d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">cv.threshold</a>(dist, 0.4, 1.0, cv.THRESH_BINARY)</div><div class="line"></div><div class="line"><span class="comment"># Dilate a bit the dist image</span></div><div class="line">kernel1 = np.ones((3,3), dtype=np.uint8)</div><div class="line">dist = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga4ff0f3318642c4f469d0e11f242f3b6c">cv.dilate</a>(dist, kernel1)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Peaks&#39;</span>, dist)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line">dist_8u = dist.astype(<span class="stringliteral">&#39;uint8&#39;</span>)</div><div class="line"></div><div class="line"><span class="comment"># Find total markers</span></div><div class="line">contours, _ = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gae4156f04053c44f886e387cff0ef6e08">cv.findContours</a>(dist_8u, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)</div><div class="line"></div><div class="line"><span class="comment"># Create the marker image for the watershed algorithm</span></div><div class="line">markers = np.zeros(dist.shape, dtype=np.int32)</div><div class="line"></div><div class="line"><span class="comment"># Draw the foreground markers</span></div><div class="line"><span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(len(contours)):</div><div class="line">    <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc">cv.drawContours</a>(markers, contours, i, (i+1), -1)</div><div class="line"></div><div class="line"><span class="comment"># Draw the background marker</span></div><div class="line"><a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">cv.circle</a>(markers, (5,5), 3, (255,255,255), -1)</div><div class="line">markers_8u = (markers * 10).astype(<span class="stringliteral">&#39;uint8&#39;</span>)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Markers&#39;</span>, markers_8u)</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"><a class="code" href="../../d3/d47/group__imgproc__segmentation.html#ga3267243e4d3f95165d55a618c65ac6e1">cv.watershed</a>(imgResult, markers)</div><div class="line"></div><div class="line"><span class="comment">#mark = np.zeros(markers.shape, dtype=np.uint8)</span></div><div class="line">mark = markers.astype(<span class="stringliteral">&#39;uint8&#39;</span>)</div><div class="line">mark = <a class="code" href="../../d2/de8/group__core__array.html#ga0002cf8b418479f4cb49a75442baee2f">cv.bitwise_not</a>(mark)</div><div class="line"><span class="comment"># uncomment this if you want to see how the mark</span></div><div class="line"><span class="comment"># image looks like at that point</span></div><div class="line"><span class="comment">#cv.imshow(&#39;Markers_v2&#39;, mark)</span></div><div class="line"></div><div class="line"><span class="comment"># Generate random colors</span></div><div class="line">colors = []</div><div class="line"><span class="keywordflow">for</span> contour <span class="keywordflow">in</span> contours:</div><div class="line">    colors.append((rng.randint(0,256), rng.randint(0,256), rng.randint(0,256)))</div><div class="line"></div><div class="line"><span class="comment"># Create the result image</span></div><div class="line">dst = np.zeros((markers.shape[0], markers.shape[1], 3), dtype=np.uint8)</div><div class="line"></div><div class="line"><span class="comment"># Fill labeled objects with random colors</span></div><div class="line"><span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(markers.shape[0]):</div><div class="line">    <span class="keywordflow">for</span> j <span class="keywordflow">in</span> range(markers.shape[1]):</div><div class="line">        index = markers[i,j]</div><div class="line">        <span class="keywordflow">if</span> index &gt; 0 <span class="keywordflow">and</span> index &lt;= len(contours):</div><div class="line">            dst[i,j,:] = colors[index-1]</div><div class="line"></div><div class="line"><span class="comment"># Visualize the final image</span></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Final Result&#39;</span>, dst)</div><div class="line"></div><div class="line"></div><div class="line"><a class="code" href="../../d7/dfc/group__highgui.html#ga5628525ad33f52eab17feebcfba38bd7">cv.waitKey</a>()</div></div><!-- fragment -->  </div> <h2>Explanation / Result </h2>
<ul>
<li>Load the source image and check if it is loaded without any problem, then show it:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Load the image</span></div><div class="line">    CommandLineParser parser( argc, argv, <span class="stringliteral">&quot;{@input | cards.png | input image}&quot;</span> );</div><div class="line">    Mat src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">imread</a>( <a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">samples::findFile</a>( parser.get&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>&gt;( <span class="stringliteral">&quot;@input&quot;</span> ) ) );</div><div class="line">    <span class="keywordflow">if</span>( src.empty() )</div><div class="line">    {</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Could not open or find the image!\n&quot;</span> &lt;&lt; endl;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Usage: &quot;</span> &lt;&lt; argv[0] &lt;&lt; <span class="stringliteral">&quot; &lt;Input image&gt;&quot;</span> &lt;&lt; endl;</div><div class="line">        <span class="keywordflow">return</span> -1;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Show the source image</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Source Image&quot;</span>, src);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Load the image</span></div><div class="line">        <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> filename = args.length &gt; 0 ? args[0] : <span class="stringliteral">&quot;../data/cards.png&quot;</span>;</div><div class="line">        Mat srcOriginal = Imgcodecs.imread(filename);</div><div class="line">        <span class="keywordflow">if</span> (srcOriginal.empty()) {</div><div class="line">            System.err.println(<span class="stringliteral">&quot;Cannot read image: &quot;</span> + filename);</div><div class="line">            System.exit(0);</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Show source image</span></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Source Image&quot;</span>, srcOriginal);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Load the image</span></div><div class="line">parser = argparse.ArgumentParser(description=<span class="stringliteral">&#39;Code for Image Segmentation with Distance Transform and Watershed Algorithm.\</span></div><div class="line"><span class="stringliteral">    Sample code showing how to segment overlapping objects using Laplacian filtering, \</span></div><div class="line"><span class="stringliteral">    in addition to Watershed and Distance Transformation&#39;</span>)</div><div class="line">parser.add_argument(<span class="stringliteral">&#39;--input&#39;</span>, help=<span class="stringliteral">&#39;Path to input image.&#39;</span>, default=<span class="stringliteral">&#39;cards.png&#39;</span>)</div><div class="line">args = parser.parse_args()</div><div class="line"></div><div class="line">src = <a class="code" href="../../d4/da8/group__imgcodecs.html#ga288b8b3da0892bd651fce07b3bbd3a56">cv.imread</a>(<a class="code" href="../../d6/dba/group__core__utils__samples.html#ga3a33b00033b46c698ff6340d95569c13">cv.samples.findFile</a>(args.input))</div><div class="line"><span class="keywordflow">if</span> src <span class="keywordflow">is</span> <span class="keywordtype">None</span>:</div><div class="line">    <a class="code" href="../../df/d57/namespacecv_1_1dnn.html#a701210a0203f2786cbfd04b2bd56da47">print</a>(<span class="stringliteral">&#39;Could not open or find the image:&#39;</span>, args.input)</div><div class="line">    exit(0)</div><div class="line"></div><div class="line"><span class="comment"># Show source image</span></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Source Image&#39;</span>, src)</div></div><!-- fragment --> </div> <div class="image">
<img src="../../source.jpeg" alt="source.jpeg"/>
</div>
<ul>
<li>Then if we have an image with a white background, it is good to transform it to black. This will help us to discriminate the foreground objects easier when we will apply the Distance Transform:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Change the background from white to black, since that will help later to extract</span></div><div class="line">    <span class="comment">// better results during the use of Distance Transform</span></div><div class="line">    Mat <a class="code" href="../../da/dd3/group__gapi__math.html#gaba076d51941328cb7ca9348b7b535220">mask</a>;</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga48af0ab51e36436c5d04340e036ce981">inRange</a>(src, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255, 255, 255), <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255, 255, 255), mask);</div><div class="line">    src.setTo(<a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0, 0, 0), mask);</div><div class="line"></div><div class="line">    <span class="comment">// Show output image</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Black Background Image&quot;</span>, src);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Change the background from white to black, since that will help later to</span></div><div class="line">        <span class="comment">// extract</span></div><div class="line">        <span class="comment">// better results during the use of Distance Transform</span></div><div class="line">        Mat src = srcOriginal.clone();</div><div class="line">        byte[] srcData = <span class="keyword">new</span> byte[(int) (src.total() * src.channels())];</div><div class="line">        src.get(0, 0, srcData);</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; src.rows(); i++) {</div><div class="line">            <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 0; j &lt; src.cols(); j++) {</div><div class="line">                <span class="keywordflow">if</span> (srcData[(i * src.cols() + j) * 3] == (byte) 255 &amp;&amp; srcData[(i * src.cols() + j) * 3 + 1] == (byte) 255</div><div class="line">                        &amp;&amp; srcData[(i * src.cols() + j) * 3 + 2] == (byte) 255) {</div><div class="line">                    srcData[(i * src.cols() + j) * 3] = 0;</div><div class="line">                    srcData[(i * src.cols() + j) * 3 + 1] = 0;</div><div class="line">                    srcData[(i * src.cols() + j) * 3 + 2] = 0;</div><div class="line">                }</div><div class="line">            }</div><div class="line">        }</div><div class="line">        src.put(0, 0, srcData);</div><div class="line"></div><div class="line">        <span class="comment">// Show output image</span></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Black Background Image&quot;</span>, src);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Change the background from white to black, since that will help later to extract</span></div><div class="line"><span class="comment"># better results during the use of Distance Transform</span></div><div class="line">src[np.all(src == 255, axis=2)] = 0</div><div class="line"></div><div class="line"><span class="comment"># Show output image</span></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Black Background Image&#39;</span>, src)</div></div><!-- fragment --> </div> <div class="image">
<img src="../../black_bg.jpeg" alt="black_bg.jpeg"/>
</div>
<ul>
<li>Afterwards we will sharpen our image in order to acute the edges of the foreground objects. We will apply a laplacian filter with a quite strong filter (an approximation of second derivative):</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Create a kernel that we will use to sharpen our image</span></div><div class="line">    Mat kernel = (Mat_&lt;float&gt;(3,3) &lt;&lt;</div><div class="line">                  1,  1, 1,</div><div class="line">                  1, -8, 1,</div><div class="line">                  1,  1, 1); <span class="comment">// an approximation of second derivative, a quite strong kernel</span></div><div class="line"></div><div class="line">    <span class="comment">// do the laplacian filtering as it is</span></div><div class="line">    <span class="comment">// well, we need to convert everything in something more deeper then CV_8U</span></div><div class="line">    <span class="comment">// because the kernel has some negative values,</span></div><div class="line">    <span class="comment">// and we can expect in general to have a Laplacian image with negative values</span></div><div class="line">    <span class="comment">// BUT a 8bits unsigned int (the one we are working with) can contain values from 0 to 255</span></div><div class="line">    <span class="comment">// so the possible negative number will be truncated</span></div><div class="line">    Mat imgLaplacian;</div><div class="line">    <a class="code" href="../../d5/df1/group__imgproc__hal__functions.html#ga42c2468ab3a1238fbf48458c57169081">filter2D</a>(src, imgLaplacian, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga4a3def5d72b74bed31f5f8ab7676099c">CV_32F</a>, kernel);</div><div class="line">    Mat sharp;</div><div class="line">    src.convertTo(sharp, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga4a3def5d72b74bed31f5f8ab7676099c">CV_32F</a>);</div><div class="line">    Mat imgResult = sharp - imgLaplacian;</div><div class="line"></div><div class="line">    <span class="comment">// convert back to 8bits gray scale</span></div><div class="line">    imgResult.convertTo(imgResult, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a>);</div><div class="line">    imgLaplacian.convertTo(imgLaplacian, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a>);</div><div class="line"></div><div class="line">    <span class="comment">// imshow( &quot;Laplace Filtered Image&quot;, imgLaplacian );</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>( <span class="stringliteral">&quot;New Sharped Image&quot;</span>, imgResult );</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Create a kernel that we will use to sharpen our image</span></div><div class="line">        Mat kernel = <span class="keyword">new</span> Mat(3, 3, CvType.CV_32F);</div><div class="line">        <span class="comment">// an approximation of second derivative, a quite strong kernel</span></div><div class="line">        <span class="keywordtype">float</span>[] kernelData = <span class="keyword">new</span> <span class="keywordtype">float</span>[(int) (kernel.total() * kernel.channels())];</div><div class="line">        kernelData[0] = 1; kernelData[1] = 1; kernelData[2] = 1;</div><div class="line">        kernelData[3] = 1; kernelData[4] = -8; kernelData[5] = 1;</div><div class="line">        kernelData[6] = 1; kernelData[7] = 1; kernelData[8] = 1;</div><div class="line">        kernel.put(0, 0, kernelData);</div><div class="line"></div><div class="line">        <span class="comment">// do the laplacian filtering as it is</span></div><div class="line">        <span class="comment">// well, we need to convert everything in something more deeper then CV_8U</span></div><div class="line">        <span class="comment">// because the kernel has some negative values,</span></div><div class="line">        <span class="comment">// and we can expect in general to have a Laplacian image with negative values</span></div><div class="line">        <span class="comment">// BUT a 8bits unsigned int (the one we are working with) can contain values</span></div><div class="line">        <span class="comment">// from 0 to 255</span></div><div class="line">        <span class="comment">// so the possible negative number will be truncated</span></div><div class="line">        Mat imgLaplacian = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.filter2D(src, imgLaplacian, CvType.CV_32F, kernel);</div><div class="line">        Mat sharp = <span class="keyword">new</span> Mat();</div><div class="line">        src.convertTo(sharp, CvType.CV_32F);</div><div class="line">        Mat imgResult = <span class="keyword">new</span> Mat();</div><div class="line">        Core.subtract(sharp, imgLaplacian, imgResult);</div><div class="line"></div><div class="line">        <span class="comment">// convert back to 8bits gray scale</span></div><div class="line">        imgResult.convertTo(imgResult, CvType.CV_8UC3);</div><div class="line">        imgLaplacian.convertTo(imgLaplacian, CvType.CV_8UC3);</div><div class="line"></div><div class="line">        <span class="comment">// imshow( &quot;Laplace Filtered Image&quot;, imgLaplacian );</span></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;New Sharped Image&quot;</span>, imgResult);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Create a kernel that we will use to sharpen our image</span></div><div class="line"><span class="comment"># an approximation of second derivative, a quite strong kernel</span></div><div class="line">kernel = np.array([[1, 1, 1], [1, -8, 1], [1, 1, 1]], dtype=np.float32)</div><div class="line"></div><div class="line"><span class="comment"># do the laplacian filtering as it is</span></div><div class="line"><span class="comment"># well, we need to convert everything in something more deeper then CV_8U</span></div><div class="line"><span class="comment"># because the kernel has some negative values,</span></div><div class="line"><span class="comment"># and we can expect in general to have a Laplacian image with negative values</span></div><div class="line"><span class="comment"># BUT a 8bits unsigned int (the one we are working with) can contain values from 0 to 255</span></div><div class="line"><span class="comment"># so the possible negative number will be truncated</span></div><div class="line">imgLaplacian = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga27c049795ce870216ddfb366086b5a04">cv.filter2D</a>(src, cv.CV_32F, kernel)</div><div class="line">sharp = np.float32(src)</div><div class="line">imgResult = sharp - imgLaplacian</div><div class="line"></div><div class="line"><span class="comment"># convert back to 8bits gray scale</span></div><div class="line">imgResult = np.clip(imgResult, 0, 255)</div><div class="line">imgResult = imgResult.astype(<span class="stringliteral">&#39;uint8&#39;</span>)</div><div class="line">imgLaplacian = np.clip(imgLaplacian, 0, 255)</div><div class="line">imgLaplacian = np.uint8(imgLaplacian)</div><div class="line"></div><div class="line"><span class="comment">#cv.imshow(&#39;Laplace Filtered Image&#39;, imgLaplacian)</span></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;New Sharped Image&#39;</span>, imgResult)</div></div><!-- fragment --> </div> <div class="image">
<img src="../../laplace.jpeg" alt="laplace.jpeg"/>
</div>
 <div class="image">
<img src="../../sharp.jpeg" alt="sharp.jpeg"/>
</div>
<ul>
<li>Now we transform our new sharpened source image to a grayscale and a binary one, respectively:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Create binary image from source image</span></div><div class="line">    Mat bw;</div><div class="line">    <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cvtColor</a>(imgResult, bw, <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#gga4e0972be5de079fed4e3a10e24ef5ef0a353a4b8db9040165db4dacb5bcefb6ea">COLOR_BGR2GRAY</a>);</div><div class="line">    <a class="code" href="../../d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">threshold</a>(bw, bw, 40, 255, <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ggaa9e58d2860d4afa658ef70a9b1115576a147222a96556ebc1d948b372bcd7ac59">THRESH_BINARY</a> | <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ggaa9e58d2860d4afa658ef70a9b1115576a95251923e8e22f368ffa86ba8bce87ff">THRESH_OTSU</a>);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Binary Image&quot;</span>, bw);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Create binary image from source image</span></div><div class="line">        Mat bw = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.cvtColor(imgResult, bw, Imgproc.COLOR_BGR2GRAY);</div><div class="line">        Imgproc.threshold(bw, bw, 40, 255, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);</div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Binary Image&quot;</span>, bw);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Create binary image from source image</span></div><div class="line">bw = <a class="code" href="../../d8/d01/group__imgproc__color__conversions.html#ga397ae87e1288a81d2363b61574eb8cab">cv.cvtColor</a>(imgResult, cv.COLOR_BGR2GRAY)</div><div class="line">_, bw = <a class="code" href="../../d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">cv.threshold</a>(bw, 40, 255, cv.THRESH_BINARY | cv.THRESH_OTSU)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Binary Image&#39;</span>, bw)</div></div><!-- fragment --> </div> <div class="image">
<img src="../../bin.jpeg" alt="bin.jpeg"/>
</div>
<ul>
<li>We are ready now to apply the Distance Transform on the binary image. Moreover, we normalize the output image in order to be able visualize and threshold the result:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Perform the distance transform algorithm</span></div><div class="line">    Mat dist;</div><div class="line">    <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ga8a0b7fdfcb7a13dde018988ba3a43042">distanceTransform</a>(bw, dist, <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ggaa2bfbebbc5c320526897996aafa1d8ebaff0d1f5be0fc152a56a9b9716d158b96">DIST_L2</a>, 3);</div><div class="line"></div><div class="line">    <span class="comment">// Normalize the distance image for range = {0.0, 1.0}</span></div><div class="line">    <span class="comment">// so we can visualize and threshold it</span></div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1b6a396a456c8b6c6e4afd8591560d80">normalize</a>(dist, dist, 0, 1.0, <a class="code" href="../../d2/de8/group__core__array.html#ggad12cefbcb5291cf958a85b4b67b6149fa9f0c1c342a18114d47b516a88e29822e">NORM_MINMAX</a>);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Distance Transform Image&quot;</span>, dist);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Perform the distance transform algorithm</span></div><div class="line">        Mat dist = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.distanceTransform(bw, dist, Imgproc.DIST_L2, 3);</div><div class="line"></div><div class="line">        <span class="comment">// Normalize the distance image for range = {0.0, 1.0}</span></div><div class="line">        <span class="comment">// so we can visualize and threshold it</span></div><div class="line">        Core.normalize(dist, dist, 0.0, 1.0, Core.NORM_MINMAX);</div><div class="line">        Mat distDisplayScaled = <span class="keyword">new</span> Mat();</div><div class="line">        Core.multiply(dist, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255), distDisplayScaled);</div><div class="line">        Mat distDisplay = <span class="keyword">new</span> Mat();</div><div class="line">        distDisplayScaled.convertTo(distDisplay, CvType.CV_8U);</div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Distance Transform Image&quot;</span>, distDisplay);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Perform the distance transform algorithm</span></div><div class="line">dist = <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ga25c259e7e2fa2ac70de4606ea800f12f">cv.distanceTransform</a>(bw, cv.DIST_L2, 3)</div><div class="line"></div><div class="line"><span class="comment"># Normalize the distance image for range = {0.0, 1.0}</span></div><div class="line"><span class="comment"># so we can visualize and threshold it</span></div><div class="line"><a class="code" href="../../d2/de8/group__core__array.html#ga7bcf47a1df78cf575162e0aed44960cb">cv.normalize</a>(dist, dist, 0, 1.0, cv.NORM_MINMAX)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Distance Transform Image&#39;</span>, dist)</div></div><!-- fragment --> </div> <div class="image">
<img src="../../dist_transf.jpeg" alt="dist_transf.jpeg"/>
</div>
<ul>
<li>We threshold the <em>dist</em> image and then perform some morphology operation (i.e. dilation) in order to extract the peaks from the above image:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Threshold to obtain the peaks</span></div><div class="line">    <span class="comment">// This will be the markers for the foreground objects</span></div><div class="line">    <a class="code" href="../../d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">threshold</a>(dist, dist, 0.4, 1.0, <a class="code" href="../../d7/d1b/group__imgproc__misc.html#ggaa9e58d2860d4afa658ef70a9b1115576a147222a96556ebc1d948b372bcd7ac59">THRESH_BINARY</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Dilate a bit the dist image</span></div><div class="line">    Mat kernel1 = Mat::ones(3, 3, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);</div><div class="line">    <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga4ff0f3318642c4f469d0e11f242f3b6c">dilate</a>(dist, dist, kernel1);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Peaks&quot;</span>, dist);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Threshold to obtain the peaks</span></div><div class="line">        <span class="comment">// This will be the markers for the foreground objects</span></div><div class="line">        Imgproc.threshold(dist, dist, 0.4, 1.0, Imgproc.THRESH_BINARY);</div><div class="line"></div><div class="line">        <span class="comment">// Dilate a bit the dist image</span></div><div class="line">        Mat kernel1 = Mat.ones(3, 3, CvType.CV_8U);</div><div class="line">        Imgproc.dilate(dist, dist, kernel1);</div><div class="line">        Mat distDisplay2 = <span class="keyword">new</span> Mat();</div><div class="line">        dist.convertTo(distDisplay2, CvType.CV_8U);</div><div class="line">        Core.multiply(distDisplay2, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255), distDisplay2);</div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Peaks&quot;</span>, distDisplay2);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Threshold to obtain the peaks</span></div><div class="line"><span class="comment"># This will be the markers for the foreground objects</span></div><div class="line">_, dist = <a class="code" href="../../d7/d1b/group__imgproc__misc.html#gae8a4a146d1ca78c626a53577199e9c57">cv.threshold</a>(dist, 0.4, 1.0, cv.THRESH_BINARY)</div><div class="line"></div><div class="line"><span class="comment"># Dilate a bit the dist image</span></div><div class="line">kernel1 = np.ones((3,3), dtype=np.uint8)</div><div class="line">dist = <a class="code" href="../../d4/d86/group__imgproc__filter.html#ga4ff0f3318642c4f469d0e11f242f3b6c">cv.dilate</a>(dist, kernel1)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Peaks&#39;</span>, dist)</div></div><!-- fragment --> </div> <div class="image">
<img src="../../peaks.jpeg" alt="peaks.jpeg"/>
</div>
<ul>
<li>From each blob then we create a seed/marker for the watershed algorithm with the help of the <a class="el" href="../../d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0">cv::findContours</a> function:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Create the CV_8U version of the distance image</span></div><div class="line">    <span class="comment">// It is needed for findContours()</span></div><div class="line">    Mat dist_8u;</div><div class="line">    dist.convertTo(dist_8u, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Find total markers</span></div><div class="line">    vector&lt;vector&lt;Point&gt; &gt; contours;</div><div class="line">    <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gadf1ad6a0b82947fa1fe3c3d497f260e0">findContours</a>(dist_8u, contours, <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga819779b9857cc2f8601e6526a3a5bc71aa7adc6d6608609fd84650f71b954b981">RETR_EXTERNAL</a>, <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gga4303f45752694956374734a03c54d5ffa5f2883048e654999209f88ba04c302f5">CHAIN_APPROX_SIMPLE</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Create the marker image for the watershed algorithm</span></div><div class="line">    Mat markers = Mat::zeros(dist.size(), <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga4067910fc388075c3ea3aa14393e83b9">CV_32S</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Draw the foreground markers</span></div><div class="line">    <span class="keywordflow">for</span> (<span class="keywordtype">size_t</span> i = 0; i &lt; contours.size(); i++)</div><div class="line">    {</div><div class="line">        <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc">drawContours</a>(markers, contours, static_cast&lt;int&gt;(i), <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(static_cast&lt;int&gt;(i)+1), -1);</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Draw the background marker</span></div><div class="line">    <a class="code" href="../../d9/db7/group__datasets__gr.html#gga610754124ced68d1f05760b5948fbb76a6f0d8b2d9e3e947b2a5c1eff9e81ee95">circle</a>(markers, <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(5,5), 3, <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255), -1);</div><div class="line">    Mat markers8u;</div><div class="line">    markers.<a class="code" href="../../d3/d63/classcv_1_1Mat.html#adf88c60c5b4980e05bb556080916978b">convertTo</a>(markers8u, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>, 10);</div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Markers&quot;</span>, markers8u);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Create the CV_8U version of the distance image</span></div><div class="line">        <span class="comment">// It is needed for findContours()</span></div><div class="line">        Mat dist_8u = <span class="keyword">new</span> Mat();</div><div class="line">        dist.convertTo(dist_8u, CvType.CV_8U);</div><div class="line"></div><div class="line">        <span class="comment">// Find total markers</span></div><div class="line">        List&lt;MatOfPoint&gt; contours = <span class="keyword">new</span> ArrayList&lt;&gt;();</div><div class="line">        Mat hierarchy = <span class="keyword">new</span> Mat();</div><div class="line">        Imgproc.findContours(dist_8u, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);</div><div class="line"></div><div class="line">        <span class="comment">// Create the marker image for the watershed algorithm</span></div><div class="line">        Mat markers = Mat.zeros(dist.size(), CvType.CV_32S);</div><div class="line"></div><div class="line">        <span class="comment">// Draw the foreground markers</span></div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; contours.size(); i++) {</div><div class="line">            Imgproc.drawContours(markers, contours, i, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(i + 1), -1);</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Draw the background marker</span></div><div class="line">        Mat markersScaled = <span class="keyword">new</span> Mat();</div><div class="line">        markers.convertTo(markersScaled, CvType.CV_32F);</div><div class="line">        Core.normalize(markersScaled, markersScaled, 0.0, 255.0, Core.NORM_MINMAX);</div><div class="line">        Imgproc.circle(markersScaled, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(5, 5), 3, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255, 255, 255), -1);</div><div class="line">        Mat markersDisplay = <span class="keyword">new</span> Mat();</div><div class="line">        markersScaled.convertTo(markersDisplay, CvType.CV_8U);</div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Markers&quot;</span>, markersDisplay);</div><div class="line">        Imgproc.circle(markers, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(5, 5), 3, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(255, 255, 255), -1);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Create the CV_8U version of the distance image</span></div><div class="line"><span class="comment"># It is needed for findContours()</span></div><div class="line">dist_8u = dist.astype(<span class="stringliteral">&#39;uint8&#39;</span>)</div><div class="line"></div><div class="line"><span class="comment"># Find total markers</span></div><div class="line">contours, _ = <a class="code" href="../../d3/dc0/group__imgproc__shape.html#gae4156f04053c44f886e387cff0ef6e08">cv.findContours</a>(dist_8u, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)</div><div class="line"></div><div class="line"><span class="comment"># Create the marker image for the watershed algorithm</span></div><div class="line">markers = np.zeros(dist.shape, dtype=np.int32)</div><div class="line"></div><div class="line"><span class="comment"># Draw the foreground markers</span></div><div class="line"><span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(len(contours)):</div><div class="line">    <a class="code" href="../../d6/d6e/group__imgproc__draw.html#ga746c0625f1781f1ffc9056259103edbc">cv.drawContours</a>(markers, contours, i, (i+1), -1)</div><div class="line"></div><div class="line"><span class="comment"># Draw the background marker</span></div><div class="line"><a class="code" href="../../d6/d6e/group__imgproc__draw.html#gaf10604b069374903dbd0f0488cb43670">cv.circle</a>(markers, (5,5), 3, (255,255,255), -1)</div><div class="line">markers_8u = (markers * 10).astype(<span class="stringliteral">&#39;uint8&#39;</span>)</div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Markers&#39;</span>, markers_8u)</div></div><!-- fragment --> </div> <div class="image">
<img src="../../markers.jpeg" alt="markers.jpeg"/>
</div>
<ul>
<li>Finally, we can apply the watershed algorithm, and visualize the result:</li>
</ul>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="comment">// Perform the watershed algorithm</span></div><div class="line">    <a class="code" href="../../d3/d47/group__imgproc__segmentation.html#ga3267243e4d3f95165d55a618c65ac6e1">watershed</a>(imgResult, markers);</div><div class="line"></div><div class="line">    Mat mark;</div><div class="line">    markers.convertTo(mark, <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga32b18d904ee2b1731a9416a8eef67d06">CV_8U</a>);</div><div class="line">    <a class="code" href="../../d2/de8/group__core__array.html#ga0002cf8b418479f4cb49a75442baee2f">bitwise_not</a>(mark, mark);</div><div class="line">    <span class="comment">//    imshow(&quot;Markers_v2&quot;, mark); // uncomment this if you want to see how the mark</span></div><div class="line">    <span class="comment">// image looks like at that point</span></div><div class="line"></div><div class="line">    <span class="comment">// Generate random colors</span></div><div class="line">    vector&lt;Vec3b&gt; colors;</div><div class="line">    <span class="keywordflow">for</span> (<span class="keywordtype">size_t</span> i = 0; i &lt; contours.size(); i++)</div><div class="line">    {</div><div class="line">        <span class="keywordtype">int</span> b = <a class="code" href="../../d2/de8/group__core__array.html#ga75843061d150ad6564b5447e38e57722">theRNG</a>().<a class="code" href="../../d1/dd6/classcv_1_1RNG.html#acde197860cea91e5aa896be8719457ae">uniform</a>(0, 256);</div><div class="line">        <span class="keywordtype">int</span> g = <a class="code" href="../../d2/de8/group__core__array.html#ga75843061d150ad6564b5447e38e57722">theRNG</a>().<a class="code" href="../../d1/dd6/classcv_1_1RNG.html#acde197860cea91e5aa896be8719457ae">uniform</a>(0, 256);</div><div class="line">        <span class="keywordtype">int</span> r = <a class="code" href="../../d2/de8/group__core__array.html#ga75843061d150ad6564b5447e38e57722">theRNG</a>().<a class="code" href="../../d1/dd6/classcv_1_1RNG.html#acde197860cea91e5aa896be8719457ae">uniform</a>(0, 256);</div><div class="line"></div><div class="line">        colors.push_back(<a class="code" href="../../dc/d84/group__core__basic.html#ga7e6060c0b8d48459964df6e1eb524c03">Vec3b</a>((<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>)b, (<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>)g, (<a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga65f85814a8290f9797005d3b28e7e5fc">uchar</a>)r));</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Create the result image</span></div><div class="line">    Mat dst = Mat::zeros(markers.size(), <a class="code" href="../../d1/d1b/group__core__hal__interface.html#ga88c4cd9de76f678f33928ef1e3f96047">CV_8UC3</a>);</div><div class="line"></div><div class="line">    <span class="comment">// Fill labeled objects with random colors</span></div><div class="line">    <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; markers.rows; i++)</div><div class="line">    {</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 0; j &lt; markers.cols; j++)</div><div class="line">        {</div><div class="line">            <span class="keywordtype">int</span> index = markers.at&lt;<span class="keywordtype">int</span>&gt;(i,j);</div><div class="line">            <span class="keywordflow">if</span> (index &gt; 0 &amp;&amp; index &lt;= static_cast&lt;int&gt;(contours.size()))</div><div class="line">            {</div><div class="line">                dst.at&lt;<a class="code" href="../../dc/d84/group__core__basic.html#ga7e6060c0b8d48459964df6e1eb524c03">Vec3b</a>&gt;(i,j) = colors[index-1];</div><div class="line">            }</div><div class="line">        }</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Visualize the final image</span></div><div class="line">    <a class="code" href="../../d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563">imshow</a>(<span class="stringliteral">&quot;Final Result&quot;</span>, dst);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='java' style='display: none;'>Java</div><div class='toggleable_div label_java' style='display: none;'> <div class="fragment"><div class="line">        <span class="comment">// Perform the watershed algorithm</span></div><div class="line">        Imgproc.watershed(imgResult, markers);</div><div class="line"></div><div class="line">        Mat mark = Mat.zeros(markers.size(), CvType.CV_8U);</div><div class="line">        markers.convertTo(mark, CvType.CV_8UC1);</div><div class="line">        Core.bitwise_not(mark, mark);</div><div class="line">        <span class="comment">// imshow(&quot;Markers_v2&quot;, mark); // uncomment this if you want to see how the mark</span></div><div class="line">        <span class="comment">// image looks like at that point</span></div><div class="line"></div><div class="line">        <span class="comment">// Generate random colors</span></div><div class="line">        Random rng = <span class="keyword">new</span> Random(12345);</div><div class="line">        List&lt;Scalar&gt; colors = <span class="keyword">new</span> ArrayList&lt;&gt;(contours.size());</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; contours.size(); i++) {</div><div class="line">            <span class="keywordtype">int</span> b = rng.nextInt(256);</div><div class="line">            <span class="keywordtype">int</span> g = rng.nextInt(256);</div><div class="line">            <span class="keywordtype">int</span> r = rng.nextInt(256);</div><div class="line"></div><div class="line">            colors.add(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(b, g, r));</div><div class="line">        }</div><div class="line"></div><div class="line">        <span class="comment">// Create the result image</span></div><div class="line">        Mat dst = Mat.zeros(markers.size(), CvType.CV_8UC3);</div><div class="line">        byte[] dstData = <span class="keyword">new</span> byte[(int) (dst.total() * dst.channels())];</div><div class="line">        dst.get(0, 0, dstData);</div><div class="line"></div><div class="line">        <span class="comment">// Fill labeled objects with random colors</span></div><div class="line">        <span class="keywordtype">int</span>[] markersData = <span class="keyword">new</span> <span class="keywordtype">int</span>[(int) (markers.total() * markers.channels())];</div><div class="line">        markers.get(0, 0, markersData);</div><div class="line">        <span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i &lt; markers.rows(); i++) {</div><div class="line">            <span class="keywordflow">for</span> (<span class="keywordtype">int</span> j = 0; j &lt; markers.cols(); j++) {</div><div class="line">                <span class="keywordtype">int</span> index = markersData[i * markers.cols() + j];</div><div class="line">                <span class="keywordflow">if</span> (index &gt; 0 &amp;&amp; index &lt;= contours.size()) {</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 0] = (byte) colors.get(index - 1).val[0];</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 1] = (byte) colors.get(index - 1).val[1];</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 2] = (byte) colors.get(index - 1).val[2];</div><div class="line">                } <span class="keywordflow">else</span> {</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 0] = 0;</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 1] = 0;</div><div class="line">                    dstData[(i * dst.cols() + j) * 3 + 2] = 0;</div><div class="line">                }</div><div class="line">            }</div><div class="line">        }</div><div class="line">        dst.put(0, 0, dstData);</div><div class="line"></div><div class="line">        <span class="comment">// Visualize the final image</span></div><div class="line">        HighGui.imshow(<span class="stringliteral">&quot;Final Result&quot;</span>, dst);</div></div><!-- fragment --> </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="comment"># Perform the watershed algorithm</span></div><div class="line"><a class="code" href="../../d3/d47/group__imgproc__segmentation.html#ga3267243e4d3f95165d55a618c65ac6e1">cv.watershed</a>(imgResult, markers)</div><div class="line"></div><div class="line"><span class="comment">#mark = np.zeros(markers.shape, dtype=np.uint8)</span></div><div class="line">mark = markers.astype(<span class="stringliteral">&#39;uint8&#39;</span>)</div><div class="line">mark = <a class="code" href="../../d2/de8/group__core__array.html#ga0002cf8b418479f4cb49a75442baee2f">cv.bitwise_not</a>(mark)</div><div class="line"><span class="comment"># uncomment this if you want to see how the mark</span></div><div class="line"><span class="comment"># image looks like at that point</span></div><div class="line"><span class="comment">#cv.imshow(&#39;Markers_v2&#39;, mark)</span></div><div class="line"></div><div class="line"><span class="comment"># Generate random colors</span></div><div class="line">colors = []</div><div class="line"><span class="keywordflow">for</span> contour <span class="keywordflow">in</span> contours:</div><div class="line">    colors.append((rng.randint(0,256), rng.randint(0,256), rng.randint(0,256)))</div><div class="line"></div><div class="line"><span class="comment"># Create the result image</span></div><div class="line">dst = np.zeros((markers.shape[0], markers.shape[1], 3), dtype=np.uint8)</div><div class="line"></div><div class="line"><span class="comment"># Fill labeled objects with random colors</span></div><div class="line"><span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(markers.shape[0]):</div><div class="line">    <span class="keywordflow">for</span> j <span class="keywordflow">in</span> range(markers.shape[1]):</div><div class="line">        index = markers[i,j]</div><div class="line">        <span class="keywordflow">if</span> index &gt; 0 <span class="keywordflow">and</span> index &lt;= len(contours):</div><div class="line">            dst[i,j,:] = colors[index-1]</div><div class="line"></div><div class="line"><span class="comment"># Visualize the final image</span></div><div class="line"><a class="code" href="../../df/d24/group__highgui__opengl.html#gaae7e90aa3415c68dba22a5ff2cefc25d">cv.imshow</a>(<span class="stringliteral">&#39;Final Result&#39;</span>, dst)</div></div><!-- fragment --> </div> <div class="image">
<img src="../../final.jpeg" alt="final.jpeg"/>
</div>
 </div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:35 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
